package compiler.emiter;

import java.util.Hashtable;

import compiler.emiter.expressiontypes.Type;

public class VariableEnumerator {
    
  /**
   * Keeps the track of counted variables.
   */
  int counter; 
  
  /**
   * Maps defined variables to their numbers.
   */
  Hashtable<String, Variable> variableToNumber; 
  
  /**
   * Constructor, setting the initial values for constant counting.
   */
  public VariableEnumerator() {
    this.counter = 0;
    this.variableToNumber = 
      new Hashtable<String, Variable>();
  }
  
  public VariableEnumerator(VariableEnumerator ve) {
    this.counter = ve.counter;
    this.variableToNumber = new Hashtable<String, Variable>(ve.variableToNumber);
  }
  
  public int size() {
    return this.variableToNumber.size();
  }
  
  /**
   * Adds a constant to the constant pool, giving it appropriate number.
   * 
   * @param name - name (value) of the constant
   * @param type - type of the constant
   * @throws JKlasyEmitterException - thrown, if value already in pool
   */
  public void addVariable(String name, Type type, Boolean isField) 
     /* throws JKlasyEmitterException */ {
   
    if (this.variableToNumber.containsKey(name)) {
      /*
      Disabled due to ANTLR's disability to handle exceptions 
      
      throw new JKlasyEmitterException(
          "Name " + name + " already in the constant pool!");
       */
      
      System.err.println("Name " + name + 
      " already enumerated!");
    }

    if (isField)
      this.variableToNumber.put(name, new Variable(name, type, 0, isField));
    else {
      this.counter++;
      this.variableToNumber.put(name, new Variable(name, type, this.counter, isField));
    }
  }
  
  /**
   * Gets the number the constant was given when added to the pool.
   * 
   * @param name - name (value) of the constant
   * @throws JKlasyEmitterException - thrown, when there is no such constant.
   */
  public Variable getVariable(String name) 
    /*  throws JKlasyEmitterException */ {
    
    
    if (!this.variableToNumber.containsKey(name)) {
    /*
    Disabled due to ANTLR's disability to handle exceptions
      throw new JKlasyEmitterException(
          "Name " + name + " not in the constant pool!");
    }
    */
      System.err.println("Name " + name + " not in the constant pool!");
    }

    return this.variableToNumber.get(name);
  }
}
